package com.xcc.netty.socket.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 * @author frosty
 * @description
 * @date 2019-12-31 31:17:12
 */


public class GroupChatClient {


    private final String HOST = "127.0.0.1";
    private final int PORT = 8761;
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;

    public GroupChatClient() throws IOException {
        selector = Selector.open();
        socketChannel= socketChannel.open(new InetSocketAddress(HOST, PORT));
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ);
        username = socketChannel.getLocalAddress().toString();
        System.out.println(username + "is ok");
    }


    //向服务器发送数据

    public void sendInfo(String msg) {
        msg = username + "说:" + msg;
        try {
            //发送消息
            socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 读取消息
     */
    public void readInfo() {

        try {
            //发送消息
            int count = selector.select();
            if (count > 0) {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if(key.isReadable()){
                        SocketChannel sc = (SocketChannel) key.channel();
                        ByteBuffer buff = ByteBuffer.allocate(1024);
                        sc.read(buff);
                        String msg = new String(buff.array());
                        System.out.println(msg.trim());
                    }
                }
             iterator.remove();

            } else {

            }


        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws Exception {
        //启动客户端
        final GroupChatClient groupChatClient = new GroupChatClient();
        //启动一个线程
        new Thread(){
            public void run() {
                while (true) {
                    System.out.println("ss");
                    groupChatClient.readInfo();
                    try {
                        Thread.currentThread().sleep(2000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

         Scanner scanner = new Scanner(System.in);
        while (true){
            String s=scanner.nextLine();
            groupChatClient.sendInfo(s);
        }

    }

}
